<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="店铺名称">
          <el-input v-model="searchForm.storeName" placeholder="店铺名称" clearable />
        </el-form-item>
        <el-form-item label="加盟人">
          <el-input v-model="searchForm.franchisee" placeholder="加盟人" clearable />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="searchForm.franchiseePhone" placeholder="联系方式" clearable />
        </el-form-item>
        <el-form-item label="微信群名">
          <el-input v-model="searchForm.wechatGroupName" placeholder="微信群名" clearable />
        </el-form-item>
        <el-form-item label="加盟时间">
          <el-date-picker
            v-model="searchForm.joinDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="起始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item label="管理费状态">
          <el-select v-model="searchForm.feeStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="已缴费" :value="1" />
            <el-option label="未缴费" :value="0" />
            <el-option label="加盟未满一年" :value="-1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-card">
      <div style="margin-bottom: 10px; font-size: 15px; color: #666;">
        共 {{ total }} 条数据
      </div>
      <el-table :data="pagedData" border stripe style="width: 100%">
        <el-table-column prop="storeName" label="店铺名称" min-width="120" />
        <el-table-column prop="franchisee" label="加盟人" min-width="100" />
        <el-table-column prop="phone" label="联系方式" min-width="120" />
        <el-table-column prop="wechatGroup" label="微信群名" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="150">
          <template #default="scope">
            <span v-if="scope.row.address">{{ scope.row.address }}</span>
            <span v-else class="no-address">暂无地址</span>
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加盟时间" min-width="120">
          <template #default="scope">
            <span v-if="scope.row.joinDate">{{ formatDate(scope.row.joinDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="managementFeeStatus" label="管理费状态" min-width="160">
          <template #default="scope">
            <el-tag :type="getFeeStatusTagType(scope.row.managementFeeStatus)" :color="getFeeStatusTagColor(scope.row.managementFeeStatus)" disable-transitions>
              {{ getFeeStatusText(scope.row.managementFeeStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="220">
          <template #default="scope">
            <template v-if="scope.row.managementFeeStatus === 0">
              <el-button size="small" type="success" @click="markPaid(scope.row)" style="margin-left: 8px">已交</el-button>
              <el-button size="small" type="info" @click="showPayments(scope.row)" style="margin-left: 8px">流水</el-button>
            </template>
            <template v-else-if="scope.row.managementFeeStatus === 1 || scope.row.managementFeeStatus === 2">
              <el-button size="small" type="info" @click="showPayments(scope.row)" style="margin-left: 8px">流水</el-button>
            </template>
            <!-- -1 或其他情况不显示任何按钮 -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 首次渲染弹窗 -->
    <el-dialog
      v-model="showDialog"
      title="未缴纳管理费提醒"
      width="450px"
      class="custom-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="dialog-header-content">
          <el-icon color="#f56c6c" size="22"><WarningFilled /></el-icon>
          <span>本月共 <b class="unpaid-count">{{unpaidList.length}}</b> 家加盟商未缴纳费用</span>
        </div>
        <el-divider />
        <el-scrollbar height="150px">
          <ul class="unpaid-list">
            <li v-for="item in unpaidList" :key="item.id" class="unpaid-list-item">
              <span class="store-name"><el-icon><Shop /></el-icon> {{item.storeName}}</span>
              <span class="contact-info"><el-icon><Phone /></el-icon> {{item.contact}}</span>
            </li>
          </ul>
        </el-scrollbar>
      </div>
      <template #footer>
        <el-button type="primary" @click="showDialog = false">知道了</el-button>
      </template>
    </el-dialog>

    <!-- 流水弹框 -->
    <el-dialog
      v-model="showPaymentsDialog"
      width="420px"
      class="payments-dialog"
      :close-on-click-modal="false"
    >
      <div class="payments-title-area">
        <div class="payments-title">{{ paymentsDialogStoreName }}</div>
        <div class="payments-subtitle">缴费流水</div>
      </div>
      <div class="payments-content">
        <div class="payments-count-card">
          <el-icon color="#409eff" size="28"><Coin /></el-icon>
          <span class="count-label">共</span>
          <span class="count-num">{{currentPayments.length}}</span>
          <span class="count-label">次缴费</span>
        </div>
        <el-divider />
        <el-empty v-if="currentPayments.length === 0" description="暂无缴费记录" />
        <div v-else class="payments-timeline-list">
          <div v-for="(item, idx) in currentPayments" :key="idx" class="timeline-item">
            <div class="timeline-dot"></div>
            <div class="timeline-content">
              <div class="timeline-date">{{ formatDate(item.logTime) }}</div>
              <div class="timeline-desc">第{{currentPayments.length - idx}}次缴费</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="showPaymentsDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { WarningFilled, Shop, Phone, Coin } from '@element-plus/icons-vue'
import axios from 'axios'

// 模拟数据移除，改为接口数据
const allData = ref([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  storeName: '',
  franchisee: '',
  franchiseePhone: '',
  wechatGroupName: '',
  joinDateRange: [], // [start, end]
  feeStatus: '',
})

const currentPage = ref(1)
const pageSize = 15

// 数据请求方法
async function fetchData() {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize,
      storeName: searchForm.storeName || undefined,
      franchisee: searchForm.franchisee || undefined,
      franchiseePhone: searchForm.franchiseePhone || undefined,
      wechatGroupName: searchForm.wechatGroupName || undefined,
      managementFeeStatus: searchForm.feeStatus === '' ? undefined : searchForm.feeStatus,
      startDate: searchForm.joinDateRange && searchForm.joinDateRange[0] ? searchForm.joinDateRange[0] : undefined,
      endDate: searchForm.joinDateRange && searchForm.joinDateRange[1] ? searchForm.joinDateRange[1] : undefined,
    }
    const { data } = await axios.post('http://121.43.176.9:8090/api/store/storesToFee', params)
    if (data && data.data) {
      const stores = data.data.records || []
      
      // 为每个门店获取地址信息
      for (const store of stores) {
        try {
          const addressRes = await axios.get(`http://121.43.176.9:8090/api/store/detail/${store.storeId}`)
          if (addressRes.data && addressRes.data.code === 200 && addressRes.data.data) {
            store.address = addressRes.data.data.address || '暂无地址'
          } else {
            store.address = '暂无地址'
          }
        } catch (e) {
          console.error('获取门店地址失败:', e)
          store.address = '暂无地址'
        }
      }
      
      allData.value = stores
      total.value = data.data.total || 0
    } else {
      allData.value = []
      total.value = 0
    }
  } catch (e) {
    ElMessage.error('数据获取失败')
    allData.value = []
    total.value = 0
  }
}

// 移除 watch 监听
// watch([() => searchForm.storeName, () => searchForm.franchisee, () => searchForm.phone, () => searchForm.wechatGroup, () => searchForm.joinMonth, () => searchForm.feeStatus, currentPage], fetchData)

onMounted(() => {
  fetchData()
})

const filteredData = computed(() => allData.value)
const pagedData = computed(() => allData.value) // 由后端分页

function onSearch() {
  currentPage.value = 1
  fetchData()
}
function onReset() {
  Object.keys(searchForm).forEach(k => {
    if (Array.isArray(searchForm[k])) searchForm[k] = []
    else searchForm[k] = ''
  })
  currentPage.value = 1
  fetchData()
}
function handlePageChange(page) {
  currentPage.value = page
  fetchData()
}

// 已交按钮逻辑
async function markPaid(row) {
  try {
    await ElMessageBox.confirm('确定要将该门店状态改为已缴费吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const { data } = await axios.post('http://121.43.176.9:8090/api/transaction-log/confirm-payment', { storeId: row.storeId })
    if (data && data.code === 200) {
      row.managementFeeStatus = 1
      ElMessage.success('状态已更新为已缴费')
    } else {
      ElMessage.error('操作失败')
    }
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('操作失败')
  }
}

// 流水弹框逻辑
const showPaymentsDialog = ref(false)
const currentPayments = ref([])
const paymentsDialogTitle = ref('缴费流水')
const paymentsDialogStoreName = ref('')
async function showPayments(row) {
  try {
    const { data } = await axios.get('http://121.43.176.9:8090/api/transaction-log/by-store', { params: { storeId: row.storeId } })
    if (data && data.data) {
      currentPayments.value = (data.data || []).slice().sort((a, b) => {
        return new Date(b.logTime).getTime() - new Date(a.logTime).getTime()
      })
    } else {
      currentPayments.value = []
    }
  } catch (e) {
    ElMessage.error('流水获取失败')
    currentPayments.value = []
  }
  paymentsDialogStoreName.value = row.storeName
  showPaymentsDialog.value = true
}

// 首次渲染弹窗逻辑
const showDialog = ref(false)
const unpaidList = computed(() => {
  return allData.value.filter(item => {
    const itemMonth = Number(item.joinDate.split('-')[1])
    return (!searchForm.joinMonth || itemMonth === Number(searchForm.joinMonth)) && item.feeStatus === '未交'
  })
})
onMounted(() => {
  if (unpaidList.value.length > 0) {
    showDialog.value = true
  }
})

function formatDate(dateStr) {
  if (!dateStr) return ''
  // 兼容 "2025-07-05T16:00:00.000+00:00" 格式
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return dateStr
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

function getFeeStatusText(status) {
  if (status === -1) return '加盟未满一年'
  if (status === 0) return '未缴费'
  if (status === 1) return '已缴费'
  return '错误，请联系后台'
}
function getFeeStatusTagType(status) {
  if (status === -1) return 'success'
  if (status === 0) return 'danger'
  if (status === 1) return 'success'
  return 'danger'
}
function getFeeStatusTagColor(status) {
  if (status === -1 || status === 1) return ''
  if (status === 0) return ''
  return '#f56c6c'
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
.search-form {
  padding-top: 18px;
}
.table-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 4px;
}
.reminded-text {
  color: #67c23a;
  margin-right: 8px;
}

/* --- Dialog Styles --- */
.custom-dialog .el-dialog__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #e7e7e7;
}
.custom-dialog .el-dialog__body {
  padding: 15px 25px 20px;
}
.dialog-header-content {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #333;
}
.dialog-header-content .el-icon {
  margin-right: 8px;
}
.unpaid-count {
  color: #f56c6c;
  font-size: 18px;
  margin: 0 4px;
}
.unpaid-list {
  margin: 0;
  padding: 0;
  list-style: none;
}
.unpaid-list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 4px;
  border-bottom: 1px solid #f0f0f0;
}
.unpaid-list-item:last-child {
  border-bottom: none;
}
.store-name, .contact-info {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #555;
}
.store-name .el-icon, .contact-info .el-icon {
  margin-right: 6px;
  font-size: 16px;
  color: #409eff;
}

/* 流水弹框美化 */
.payments-dialog .el-dialog__header {
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding-bottom: 0;
}
.payments-title-area {
  text-align: center;
  margin-top: 10px;
  margin-bottom: 8px;
}
.payments-title {
  font-size: 20px;
  font-weight: bold;
  color: #222;
}
.payments-subtitle {
  font-size: 13px;
  color: #8c8c8c;
  margin-top: 2px;
  letter-spacing: 1px;
}
.payments-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 8px;
}
.payments-count-card {
  background: #f0f7ff;
  border-radius: 12px;
  padding: 14px 32px 10px 32px;
  display: flex;
  align-items: center;
  font-size: 17px;
  color: #409eff;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px #e6f7ff;
}
.count-label {
  margin: 0 2px;
  font-size: 15px;
  color: #409eff;
}
.count-num {
  font-size: 22px;
  font-weight: bold;
  color: #2d8cf0;
  margin: 0 4px;
}
.payments-timeline-list {
  width: 100%;
  margin-top: 10px;
}
.timeline-item {
  display: flex;
  align-items: flex-start;
  background: #f8fafc;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px 18px 10px 12px;
  box-shadow: 0 1px 4px #f0f1f2;
}
.timeline-dot {
  width: 12px;
  height: 12px;
  background: #67c23a;
  border-radius: 50%;
  margin-top: 6px;
  margin-right: 14px;
  box-shadow: 0 0 0 2px #e1f3d8;
}
.timeline-content {
  flex: 1;
}
.timeline-date {
  font-size: 15px;
  color: #222;
  font-weight: 500;
}
.timeline-desc {
  font-size: 13px;
  color: #888;
  margin-top: 2px;
}

/* 地址样式 */
.no-address {
  color: #999;
  font-size: 13px;
  font-style: italic;
}
</style> 